SPB Git

Repository Public

route.ts 6.9 KB 112 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | ACADEMIC RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * PROJECT METADATA8 * -----------------------------------------------------------------------------9 * Project          : UQO Éval10 * File             : src/app/api/metre/assignments/[id]/route.ts11 * Module           : app12 * Repository       : https://git.spboucher.ai/uqo-eval13 * Project Website  : https://www.uqo-eval.app14 * Created          : 2026-10-2815 * Last Modified    : 2026-10-2816 *17 * =============================================================================18 * SOFTWARE MAINTAINER & AFFILIATION19 * =============================================================================20 *21 * Maintainer       : Simon-Pierre Boucher22 * Position         : Professor of Finance23 * Institution      : Université du Québec en Outaouais (UQO)24 * Department       : Département des sciences administratives25 * Website          : https://spboucher.ai26 * Git              : https://git.spboucher.ai27 *28 * Research Contact : research@spboucher.ai29 * Direct Contact   : simon@spboucher.ai30 * Security/Admin   : admin@spboucher.ai31 *32 * The affiliation is descriptive. It is not an institutional endorsement,33 * a license grant or a determination of ownership.34 *35 * =============================================================================36 * COPYRIGHT, AUTHORSHIP & DATA37 * =============================================================================38 *39 * Copyright (c) the author(s) of this work.40 * Ownership is not asserted by this notice; see the repository records.41 *42 * This header identifies the maintainer of the software. Scientific43 * authorship of any associated paper is stated in the paper itself and44 * is not changed by this notice. Datasets and third-party materials45 * remain the property of their respective owners and licensors.46 *47 * This file is governed by the applicable project license, copyright48 * notices, institutional agreements and relevant law.49 *50 * =============================================================================51 * LICENSE & MAINTENANCE52 * =============================================================================53 *54 * License          : None specified (no license file in this repository)55 * Classification   : Public56 *57 * =============================================================================58 * END OF SP BOUCHER SOURCE HEADER59 * =============================================================================60 */6162// UQO Éval — Métré : un devoir — détail (corrigé réservé enseignant/admin), remise par l'étudiant, notation.63import { NextRequest, NextResponse } from "next/server";64import { randomUUID } from "crypto";65import { HttpError, handle, readJson, requireProject, requireUser } from "@/lib/metre/auth";66import { audit } from "@/lib/metre/db";67import { getVersion } from "@/lib/metre/estimates";6869export const runtime = "nodejs";7071export async function GET(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {72  return handle(async () => {73    const { id } = await params; const ctx = requireUser(req);74    const a = ctx.db.prepare("SELECT id, course, title, instructions, template_project_id templateProjectId, due_at dueAt, created_by createdBy, active, created_at createdAt, answer_key_json answerKey FROM metre_assignments WHERE id=?").get(id) as Record<string, unknown> | undefined;75    if (!a) throw new HttpError(404, "Devoir introuvable.");76    const staff = ctx.user.role === "instructor" || ctx.user.role === "admin";77    if (!staff) delete a.answerKey; // garde serveur : jamais de corrigé pour un étudiant78    else a.answerKey = a.answerKey ? JSON.parse(String(a.answerKey)) : null;79    const submissions = staff80      ? ctx.db.prepare("SELECT s.id, s.user_id userId, u.display_name userName, s.project_id projectId, s.estimate_version_id versionId, s.submitted_at submittedAt, s.grade, s.feedback, s.graded_at gradedAt, v.total FROM metre_submissions s JOIN metre_users u ON u.id=s.user_id LEFT JOIN metre_estimate_versions v ON v.id=s.estimate_version_id WHERE s.assignment_id=? ORDER BY s.submitted_at DESC").all(id)81      : ctx.db.prepare("SELECT s.id, s.project_id projectId, s.estimate_version_id versionId, s.submitted_at submittedAt, s.grade, s.feedback, s.graded_at gradedAt FROM metre_submissions s WHERE s.assignment_id=? AND s.user_id=?").all(id, ctx.user.id);82    return NextResponse.json({ assignment: a, submissions });83  });84}8586/** Étudiant : remise {projectId, versionId}. Enseignant : notation {submissionId, grade, feedback}. */87export async function POST(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {88  return handle(async () => {89    const { id } = await params; const ctx = requireUser(req);90    const a = ctx.db.prepare("SELECT id, active FROM metre_assignments WHERE id=?").get(id) as { id: string; active: number } | undefined;91    if (!a) throw new HttpError(404, "Devoir introuvable.");92    const b = await readJson<Record<string, unknown>>(req);93    if (typeof b.submissionId === "string") {94      if (ctx.user.role !== "instructor" && ctx.user.role !== "admin") throw new HttpError(403, "Notation réservée aux enseignants.");95      const grade = b.grade == null ? null : Number(b.grade);96      if (grade != null && (!Number.isFinite(grade) || grade < 0 || grade > 100)) throw new HttpError(400, "Note 0–100.");97      ctx.db.prepare("UPDATE metre_submissions SET grade=?, feedback=?, graded_by=?, graded_at=datetime('now') WHERE id=? AND assignment_id=?").run(grade, typeof b.feedback === "string" ? b.feedback.slice(0, 4000) : null, ctx.user.id, b.submissionId, id);98      audit(ctx.db, { userId: ctx.user.id, role: ctx.user.role, action: "assignment.grade", entityType: "submission", entityId: b.submissionId, ip: ctx.ip });99      return NextResponse.json({ ok: true });100    }101    if (!a.active) throw new HttpError(409, "Devoir fermé.");102    const projectId = String(b.projectId ?? ""), versionId = String(b.versionId ?? "");103    requireProject(ctx, projectId, "owner");104    const v = getVersion(ctx.db, versionId);105    if (!v || v.projectId !== projectId) throw new HttpError(400, "Révision inconnue pour ce projet.");106    const sid = randomUUID();107    ctx.db.prepare("INSERT INTO metre_submissions(id,assignment_id,user_id,project_id,estimate_version_id) VALUES(?,?,?,?,?) ON CONFLICT(assignment_id,user_id) DO UPDATE SET project_id=excluded.project_id, estimate_version_id=excluded.estimate_version_id, submitted_at=datetime('now'), grade=NULL, feedback=NULL, graded_at=NULL").run(sid, id, ctx.user.id, projectId, versionId);108    audit(ctx.db, { userId: ctx.user.id, role: ctx.user.role, action: "assignment.submit", entityType: "assignment", entityId: id, projectId, details: { versionId }, ip: ctx.ip });109    return NextResponse.json({ ok: true }, { status: 201 });110  });111}112
Files main
Menu

Theme